package com.example.c94s3plyhyfc.biz;

import com.example.c94s3plyhyfc.bean.User;
import com.example.c94s3plyhyfc.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;

import javax.annotation.Resource;

@Service
@Transactional(rollbackFor = BizException.class)
public class UserBiz {

    @Resource
    private UserMapper um;

    public User login(User u, Errors errors) throws BizException {
        User user = null;
        if (errors.hasErrors() == false) {
            user = um.selectForLogin(u.getName(), u.getPwd());
        }
        if (errors.hasErrors()) {
            throw new BizException("字段验证错误!", errors.getAllErrors());
        }
        if (user == null) {
            errors.reject("nameOrPwdError", "用户名或密码错误");
            throw new BizException("用户名或密码错误!", errors.getAllErrors());
        }
        return user;
    }

    public void register(User u, Errors errors) throws BizException {
        int cnt = um.countByName(u.getName());
        if(cnt > 0) {
            errors.rejectValue("name", "nameDup...","该用户名已经被注册!");
        }
        if (errors.hasErrors()) {
            throw new BizException("字段验证错误!", errors.getAllErrors());
        }
        um.insert(u);
    }

}
